package com.zhang.shopcar.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.zhang.shopcar.base.MyApplication;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class UIUtils {

    public static SPUtils mSp = new SPUtils(getContext());
    private static String timeStr;
/*
    *//**
     * 第一个和最后两个红色
     *//*
    public static SpannableString getPrice(String money) {

        SpannableString price = new SpannableString("¥" + money);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_small), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_big), 1, money.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_small), money.length() - 1, money.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return price;
    }


    *//**
     * 第一个和最后两个橘黄色
     *//*
    public static SpannableString getOrangePrice(String money) {

        SpannableString price = new SpannableString("¥" + money);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_14small), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_18big), 1, money.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_14small), money.length() - 1, money.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return price;
    }

    *//**
     * 第一个和最后两个橘黄色大的20
     *//*
    public static SpannableString getOrangePriceSuper(String money) {

        SpannableString price = new SpannableString("¥" + money);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_14small), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_20big), 1, money.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_14small), money.length() - 1, money.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return price;
    }

    *//**
     * 最后四个白色
     *//*
    public static SpannableString lastTextWhite(String value) {

        SpannableString pvvalue = new SpannableString(value);
        pvvalue.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_superbig_white_24), 0, value.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        pvvalue.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_superbig_white_12), value.length() - 4, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return pvvalue;
    }

    *//**
     * 最后一个灰色
     *//*
    public static SpannableString lastTextGray(String value) {

        SpannableString pvvalue = new SpannableString(value);
        pvvalue.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_14small), 0, value.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        pvvalue.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_14gray), value.length() - 1, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return pvvalue;
    }

    *//**
     * 第一个和最后一个橘黄色
     *//*
    public static SpannableString lastTextOrange(String value) {

        SpannableString pvvalue = new SpannableString(value);
        pvvalue.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_14small), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        pvvalue.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_20big), 1, value.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        pvvalue.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_orange_14small), value.length() - 1, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return pvvalue;
    }

    *//**
     * 前五个不变
     *//*
    public static SpannableString firstFiveOrange(String townUp) {
        SpannableString village = new SpannableString(townUp);
        village.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_big_level_gray), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        village.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_big_level_orange), 5, townUp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        return village;
    }

    *//**
     * 前两个和最后两个orange
     *//*
    public static SpannableString firstAndLastTwoOrange(String levelUp) {

        SpannableString price = new SpannableString(levelUp);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_big_level_gray), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_big_level_orange), 2, levelUp.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_big_level_gray), levelUp.length() - 2, levelUp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //     SpannableString totlePV = UIUtils.getPrice( UIUtils.getDecimalFormat().format(mApplyAgencyaBean.getTotalPV()));

        return price;
    }

    *//**
     * 第一个和最后两个白色小
     *//*
    public static SpannableString getWhitePrice(String money) {

        SpannableString price = new SpannableString("¥" + money);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_big_white), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_superbig_white_20), 1, money.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        price.setSpan(new TextAppearanceSpan(UIUtils.getContext(), R.style.money_text_big_white), money.length() - 2, money.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return price;
    }*/


    //得到价格格式转换
    public static DecimalFormat getDecimalFormat() {
        return MyApplication.getDecimalFormat();
    }


    /**
     * 得到上下文
     */
    public static Context getContext() {
        return MyApplication.getContext();
    }

    //得到商品详情id 和 数量
    public static Map<Long, Integer> getMap() {
        return MyApplication.getGoodsMap();
    } //得到商品详情id 和 数量

    public static Map<Long, Integer> getGoodsShareMap() {
        return MyApplication.getmGoodsSharesMap();
    }

    /*  public static String getLocationCity(){
          return MyApplication.getLocationCity();
      }*/

    public static List getHistoryList() {
        return MyApplication.getHistoryList();
    }


    public static List getStockAttriList() {
        return MyApplication.getStockAttriList();
    }

    //得到商家id
    public static Map getShopMap() {
        return MyApplication.getShopMap();

    }


    //得到留言
    public static Map getRemarkMap() {
        return MyApplication.getRemarkMap();
    }

    //得到留言
    public static boolean getIsSelectLocationCity() {
        return MyApplication.isSelectLocationCity();
    }


    // 添加Activity到容器中
    public static void addActivity(Activity activity) {
        MyApplication.getMyListActivity().add(activity);
    }

    //得到历史访问城市
    public static Map getHistoryMap() {
        return MyApplication.getHistoryMap();
    }

    public static Map<String, String> getCityMap() {
        return MyApplication.getCityMap();
    }

    public static List getCityList() {
        return MyApplication.getCityList();
    }

    /**
     * 得到Resource对象
     */
    public static Resources getResources() {
        return getContext().getResources();
    }

    /**
     * 得到string.xml中的字符
     */
    public static String getString(int resId) {
        return getResources().getString(resId);
    }

    /**
     * 得到string.xml中的字符,带占位符
     */
    public static String getString(int resId, Object... formatArgs) {
        return getResources().getString(resId, formatArgs);
    }

    /**
     * 得到string.xml中的字符数组
     */
    public static String[] getStringArr(int resId) {
        return getResources().getStringArray(resId);
    }

    /**
     * 得到color.xml中的颜色值
     */
    public static int getColor(int resId) {
        return getResources().getColor(resId);
    }

    /**
     * 得到应用程序的包名
     */
    public static String getPackageName() {
        return getContext().getPackageName();
    }

    /**
     * 得到主线程的id
     */
    public static long getMainThreadId() {
        return MyApplication.getMainThreadId();
    }

    /**
     * 得到主线程的handler
     */
    public static Handler getHandler() {
        return MyApplication.getHandler();
    }

    /**
     * 安全的执行一个task
     */
    public static void postTaskSafely(Runnable task) {
        // 得到当前线程的id
        long curThreadId = android.os.Process.myTid();
        long mainThreadId = getMainThreadId();

        if (curThreadId == mainThreadId) {
            // 如果调用该方法的线程是在主线程-->直接执行任务
            task.run();
        } else {
            // 如果调用该方法的线程是在子线程-->把任务post到主线程handler去执行

            // 主线程的handler
            Handler handler = getHandler();
            handler.post(task);
        }
    }


    /*
    * 多次点击只显示一次
    *
    * */
    private static Toast toast;

    public static void showToast(Context context,
                                 String content) {
        if (toast == null) {
            toast = Toast.makeText(context,
                    content,
                    Toast.LENGTH_SHORT);
        } else {
            toast.setText(content);
        }
        toast.show();
    }


    /**
     * dip-->px
     *
     * @param
     * @return
     */
    public static int dip2Px(int dip) {
        // px/dp = density
        // px/(ppi/160) = px
        float density = getResources().getDisplayMetrics().density;//1.5
        int ppi = getResources().getDisplayMetrics().densityDpi;//240
        int px = (int) (dip * density + .5f);
        return px;
    }

    /**
     * px-->dip
     *
     * @param
     * @return
     */
    public static int px2Dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String getPhoneIp() {

        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }


        return null;
    }


    public String GetIpAddress() throws SocketException {
        String ipaddress = "";
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface intf = netInterfaces.nextElement();
                if (intf.getName().toLowerCase().equals("eth0") || intf.getName().toLowerCase().equals("wlan0")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("%")) {// ipV6的地址
                                ipaddress = ipaddress;
                            }
                        }
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
// final ContentResolver mContentResolver = getContentResolver();
// Settings.System.putInt( mContentResolver,
// Settings.System.WIFI_USE_STATIC_IP, 1);
// Settings.System.putString( mContentResolver,
// Settings.System.WIFI_STATIC_IP, "你的ip地址");

        return ipaddress;
    }


    public static String getMapKey(Map<Long, Integer> map) {


        // 第三种：推荐，尤其是容量大时
        StringBuilder sb = new StringBuilder();
        System.out.println(map.size());

        String keyStrTEM = "";
        if (map.size() > 1) {
            for (Map.Entry<Long, Integer> entry : map.entrySet()) {

                sb.append(entry.getKey());
                sb.append(",");

            }
            String keyStr = sb.toString();
            keyStrTEM = keyStr.substring(0, keyStr.length() - 1);
            //return keyStrTEM;
        } else if (map.size() == 1) {
            for (Map.Entry<Long, Integer> entry : map.entrySet()) {

                keyStrTEM = entry.getKey() + "";
            }


        }


        return keyStrTEM;
    }

    public static String getMapValue(Map<Long, Integer> map) {


        // 第三种：推荐，尤其是容量大时
        StringBuilder sb = new StringBuilder();
        System.out.println(map.size());

        String keyStrTEM = "";
        if (map.size() > 1) {
            for (Map.Entry<Long, Integer> entry : map.entrySet()) {

                sb.append(entry.getValue());
                sb.append(",");

            }
            String keyStr = sb.toString();
            keyStrTEM = keyStr.substring(0, keyStr.length() - 1);
            // return keyStrTEM;
        } else if (map.size() == 1) {
            for (Map.Entry<Long, Integer> entry : map.entrySet()) {

                keyStrTEM = entry.getValue() + "";
            }


        }


        return keyStrTEM;
    }


    public static String getShopIdForMapValue(Map<String, Integer> map) {


        // 第三种：推荐，尤其是容量大时
        StringBuilder sb = new StringBuilder();
        System.out.println(map.size());

        String keyStrTEM = "";
        if (map.size() > 1) {
            for (Map.Entry<String, Integer> entry : map.entrySet()) {

                sb.append(entry.getValue());
                sb.append(",");

            }
            String keyStr = sb.toString();
            keyStrTEM = keyStr.substring(0, keyStr.length() - 1);
            //  return keyStrTEM;
        } else if (map.size() == 1) {
            for (Map.Entry<String, Integer> entry : map.entrySet()) {

                keyStrTEM = entry.getValue() + "";
            }


        }


        return keyStrTEM;
    }


    public static String getRemarkForMapValue(Map<String, String> map) {


        // 第三种：推荐，尤其是容量大时
        StringBuilder sb = new StringBuilder();
        System.out.println(map.size());

        String keyStrTEM = "";
        if (map.size() > 1) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (entry.getValue() == "") {
                    sb.append("1");
                    sb.append("@");
                } else {
                    sb.append(entry.getValue());
                    sb.append("@");
                }
            }
            String keyStr = sb.toString();
            keyStrTEM = keyStr.substring(0, keyStr.length() - 1);
            return keyStrTEM;
        } else if (map.size() == 1) {
            for (Map.Entry<String, String> entry : map.entrySet()) {

                keyStrTEM = entry.getValue() + "";
            }


        }


        return keyStrTEM;
    }

    public static String getDetailsIdForList(List<Long> list) {
        StringBuilder sb = new StringBuilder();
        String result = "";
        if (list.size() != 0) {

            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i));
                sb.append(",");

            }
            String str = sb.toString();
            result = str.substring(0, str.length() - 1);

        } else if (list.size() == 1) {
            result = list.get(0) + "";

        }
        return result;
    }


    public static String getTimeCha(String timebegin, String timeend) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        Date d1 = null;
        try {
            d1 = df.parse(timebegin);
            Date d2 = df.parse(timeend);
            long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别

            long days = diff / (1000 * 60 * 60 * 24);

            long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);

            long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
            timeStr = "" + days + hours + minutes;

        } catch (ParseException e) {
            e.printStackTrace();
        }


        return timeStr;
    }


    public static void setMargins(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

    /**
     * 身份证号码验证
     */
    public static boolean personIdValidation(String text) {
        String regx = "[0-9]{17}X";
        String regx2 = "[0-9]{17}x";
        String reg1 = "[0-9]{15}";
        String regex = "[0-9]{18}";
        return text.matches(regx) || text.matches(reg1) || text.matches(regex) || text.matches(regx2);
    }

    /**
     * 电话格式验证
     */
    public static boolean isFormater(String number) {
        String numRex = "1[35478]{1}[0-9]{9} ";

        return number.matches(numRex);
    }


    public static boolean isMobile(final String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    /**
     * 电话号码验证
     *
     * @param str
     * @return 验证通过返回true
     * @author ：shijing
     * 2016年12月5日下午4:34:21
     */
    public static boolean isPhone(final String str) {
        Pattern p1 = null, p2 = null;
        Matcher m = null;
        boolean b = false;
        p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");  // 验证带区号的
        p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");         // 验证没有区号的
        if (str.length() > 9) {
            m = p1.matcher(str);
            b = m.matches();
        } else {
            m = p2.matcher(str);
            b = m.matches();
        }
        return b;
    }


    /**
     * 3des加密
     */
/*    public static String getDesStr(String pwd) throws Exception {


        byte[] key = Base64.decode("eGtxMlp2M0dZMmhwYVl0c2IwOHZjSHR5".getBytes(), Base64.DEFAULT);

        byte[] data = pwd.getBytes("UTF-8");

        byte[] str3 = des3EncodeECB(key, data);
        pwd = new String(Base64.encode(str3, Base64.DEFAULT), "UTF-8").trim();


        return pwd;
    }*/


    /**
     * 校验邮箱
     *
     * @param email
     * @return 校验通过返回true，否则返回false
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    public static boolean isEmail(String email) {
        return Pattern.matches(REGEX_EMAIL, email);
    }

}
